package com.shijun.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.BitmapRequestBuilder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.shijun.bean.ConfigModle;
import com.shijun.bean.GroupModle;
import com.shijun.bean.ImageModle;
import com.shijun.config.TableShowImageConfig;
import com.shijun.pullrecyclerviewdemo.R;

import java.util.List;

/**
 * Created by zhushijun on 2017/12/30 0030.
 */

public class CustomTableShowImageView extends LinearLayout {
    private Context context;
    private List<String> imgsData;
    private int type;
    private ConfigModle config;
    private LinearLayout tableShowRootView;
    private int rootViewWidth;

    public CustomTableShowImageView(Context context, List<String> imgs, int type, int rootViewWidth) {
        super(context);
        this.context = context;
        this.imgsData = imgs;
        this.type = type;
        this.rootViewWidth = rootViewWidth;
        initView();
    }

    private void initView() {
        config = new TableShowImageConfig(context, type, imgsData).getConfig();
        tableShowRootView = getViewByConfig(config);
        addView(tableShowRootView);
    }

    private LinearLayout getViewByConfig(ConfigModle config) {

        LinearLayout rootView = new LinearLayout(context);
        LayoutParams rootParams = new LayoutParams(config.getWidth(), config.getHeight());
        rootParams.setMargins(config.getMarginLeft(), config.getMarginTop(), config.getMarginRight(), config.getMarginBottom());
        rootView.setOrientation(LinearLayout.VERTICAL);
        rootView.setLayoutParams(rootParams);
        if (config.getBackgroundId() != 0) {
            rootView.setBackgroundResource(config.getBackgroundId());
        }

        List<GroupModle> groups = config.getGroups();
        if (groups == null || groups.size() == 0) {
            return rootView;
        }
        for (int i = 0; i < groups.size(); i++) {
            GroupModle group = groups.get(i);
            LinearLayout linearLayout = getGroupLinearLayout(i, group, config.getInterval());
            rootView.addView(linearLayout);
        }
        return rootView;
    }

    private LinearLayout getGroupLinearLayout(int _Y, GroupModle group, int interval) {
        LinearLayout linearLayout = new LinearLayout(context);
        LayoutParams gtoupParams = new LayoutParams(group.getWidth(), group.getHeight());
        gtoupParams.weight = group.getWeight();
        gtoupParams.setMargins(group.getMarginLeft(), interval == 0 ? group.getMarginTop() : (interval / 2), group.getMarginRight(), interval == 0 ? group.getMarginBottom() : (interval / 2));
        linearLayout.setLayoutParams(gtoupParams);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        List<ImageModle> imgs = group.getImages();

        if (imgs == null || imgs.size() == 0) {
            return linearLayout;
        }
        for (int i = 0; i < imgs.size(); i++) {
            ImageModle img = imgs.get(i);
            ImageView imageView = getImageView(_Y, img, group.getInterval());
            linearLayout.addView(imageView);
        }

        return linearLayout;
    }

    private ImageView getImageView(int _Y, final ImageModle img, final int interval) {
        final CircleImageView image = new CircleImageView(context, context.getResources().getDimensionPixelSize(R.dimen.x20));
        int width = img.getWidth();
        int height = img.getHeight();
        int weight = img.getWeight();
        if (weight != 0) {
            width = config.getWidthByWeight(_Y, rootViewWidth) * weight;
            height = width;
        }
        final LayoutParams imgParams = new LayoutParams(width, height);
        imgParams.setMargins(interval == 0 ? img.getMarginLeft() : (interval / 2), img.getMarginTop(), interval == 0 ? img.getMarginRight() : (interval / 2), img.getMarginBottom());
        imgParams.weight = img.getWeight();
        image.setLayoutParams(imgParams);
        image.setScaleType(ImageView.ScaleType.CENTER_CROP);
        String imgUrl = img.getImageUrl();
        if (imgUrl != null && !"".equals(imgUrl)) {
            BitmapRequestBuilder<String, Bitmap> builder = Glide.with(context)
                    .load(img.getImageUrl())
                    .asBitmap()
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .override(rootViewWidth, (int) (rootViewWidth*0.7f))
                    .placeholder(R.drawable.ic_launcher_background);
            if (imgsData.size() == 1) {
                builder.into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        Log.i("TAG","resource width:"+resource.getWidth()+" resource height:"+resource.getHeight());
                        int[] result = getWidthAndHeightBySelfAdaption(resource.getWidth(), resource.getHeight());
                        Log.i("TAG","width:"+result[0]+" height:"+result[1]);
                        LayoutParams imgParams = new LayoutParams(result[0], result[1]);
                        imgParams.setMargins(interval == 0 ? img.getMarginLeft() : (interval / 2), img.getMarginTop(), interval == 0 ? img.getMarginRight() : (interval / 2), img.getMarginBottom());
                        imgParams.weight = img.getWeight();
                        image.setLayoutParams(imgParams);
                        Bitmap newBitmap = null;
                        if (resource.getWidth() == result[0] && resource.getHeight() == result[1]) {
                            newBitmap = resource;
                        } else {
                            newBitmap = Bitmap.createScaledBitmap(resource, result[0], result[1], true);
                            resource.recycle();
                        }
                        image.setImageBitmap(newBitmap);
                        image.invalidate();
                    }
                });

            } else {
                builder.override(width, height).into(image);
            }
        }
        return image;
    }

    private int[] getWidthAndHeightBySelfAdaption(int imgWidth, int imgHeight) {
        int width = 0;
        int height = 0;
        if (imgWidth > rootViewWidth || imgHeight > rootViewWidth * 0.7f) {
            if (imgHeight * 0.7f > imgWidth) {
                height = (int) (rootViewWidth * 0.7f);
                width = (int) (((float) height / (float) imgHeight) * (float) imgWidth);
            } else {
                width = rootViewWidth;
                height = (int) (((float) rootViewWidth / (float) imgWidth) * (float) imgHeight);
            }
        } else {
            width = imgWidth;
            height = imgHeight;
        }
        return new int[]{width, height};
    }

    public LinearLayout getTableShowRootView() {
        return tableShowRootView;
    }

}
